package com.jingjin.humanityservice.util.ranking;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.jingjin.humanityservice.util.ranking.cacheData.CacheDataInRedis;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Component;

import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.time.Instant;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

@Component
public class CSDNRankingHandler {

    private static final HttpClient httpClient = HttpClient.newHttpClient();

    @Resource
    private ObjectMapper objectMapper;

    @Resource
    private CacheDataInRedis cacheDataInRedis;


    public Map<String, Object> handleRoute(boolean noCache) throws Exception {
        Map<String, Object> listResult = getList(noCache);
        // 缓存数据到redis
        cacheDataInRedis.cacheData("csdn:hotSearch", listResult);

        Map<String, Object> routeData = new LinkedHashMap<>();
        routeData.put("name", "csdn");
        routeData.put("favicon", "https://www.blog.csdn.net/favicon.ico");
        routeData.put("title", "CSDN");
        Instant nowTime = Instant.now();
        // 将当前时间戳转换为上海时区
        ZonedDateTime Shanghai = nowTime.atZone(ZoneId.of("Asia/Shanghai"));
        routeData.put("nowTime", Shanghai);
        routeData.put("type", "排行榜");
        routeData.put("link", "https://www.csdn.net/");
        routeData.put("total", ((List<?>) listResult.get("data")).size());

        List<Map<String, Object>> dataList = addIndexToDataList((List<Map<String, Object>>) listResult.get("data"));
        routeData.put("data", dataList);

        // 缓存数据到redis
        cacheDataInRedis.cacheData("csdn:hotSearch", routeData);

        return routeData;
    }

    private List<Map<String, Object>> addIndexToDataList(List<Map<String, Object>> dataList) {
        return IntStream.range(0, dataList.size())
                .mapToObj(index -> {
                    Map<String, Object> newItem = new LinkedHashMap<>();
                    newItem.put("index", index + 1);
                    newItem.putAll(dataList.get(index));
                    return newItem;
                })
                .collect(Collectors.toList());
    }

    private Map<String, Object> getList(boolean noCache) throws Exception {
        String url = "https://blog.csdn.net/phoenix/web/blog/hot-rank?page=0&pageSize=30";
        Map<String, Object> result = get(url, noCache);

        if (result != null && result.containsKey("data")) {
            List<Map<String, Object>> list = (List<Map<String, Object>>) result.get("data");

            List<Map<String, Object>> mappedList = list.stream().map(v -> {
                Map<String, Object> item = new LinkedHashMap<>();
                item.put("title", v.get("articleTitle"));
                item.put("url", v.get("articleDetailUrl"));
                item.put("mobileUrl", v.get("articleDetailUrl"));
                return item;
            }).collect(Collectors.toList());

            Map<String, Object> resultMap = new LinkedHashMap<>();
            resultMap.put("fromCache", result.getOrDefault("fromCache", false));
            resultMap.put("updateTime", result.getOrDefault("updateTime", 0L));
            resultMap.put("data", mappedList);

            return resultMap;
        }

        throw new RuntimeException("Failed to retrieve list data from the API.");
    }

    private Map<String, Object> get(String url, boolean noCache) throws Exception {
        HttpRequest request = HttpRequest.newBuilder()
                .uri(URI.create(url))
                .header("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/123.0.0.0 Safari/537.36")
                .build();

        HttpResponse<String> response = httpClient.send(request, HttpResponse.BodyHandlers.ofString());
        JsonNode resultNode = objectMapper.readTree(response.body());

        return objectMapper.convertValue(resultNode, new TypeReference<Map<String, Object>>() {});
    }

    public Map<String, Object> getRouteAndDataCombined(boolean noCache) throws Exception {
        return handleRoute(noCache);
    }

    public Map<String, Object> getCSDNRanking() throws Exception {
        return getRouteAndDataCombined(false);
    }
}
